package ps.server;

import java.util.TreeMap;
import java.util.Vector;

import ps.server.net.ClientInfo;



public class ClientManager {
    
    Object clientListLock = new Object();
    
    private ClientInfo[] clientInfos = new ClientInfo[0];
    private Vector<ClientInfo> clientList = new Vector<ClientInfo>(50);
    
    private ClientInfo[] createClientInfoArray() {
        return clientList.toArray(new ClientInfo[clientList.size()]);
    }
    
    public ClientInfo[] getAllClientInfos() {
        return clientInfos;
    }
    
    public void addClient(ClientInfo clientInfo) {
        synchronized (clientListLock) {
            clientList.add(clientInfo);
            clientInfos = createClientInfoArray();
        }
    }
    
    public void removeClientInfo(ClientInfo clientInfo) {
        clientInfo.close();
        
        synchronized (clientListLock) {
            clientList.remove(clientInfo);
            clientInfos = createClientInfoArray();
        }
    }
    
    public ClientInfo getClientInfoByUserName(String userName) {
        synchronized (clientListLock) {
            for (ClientInfo clientInfo : clientInfos) {
                if (clientInfo.getUser() != null && clientInfo.getUser().getName().equals(userName)) {
                    return clientInfo;
                }
            }
        }
        return null;
    }
    
    public ClientInfo[] getClientInfosSortedByUserName() {
        ClientInfo[] ret;
        synchronized (clientListLock) {
            TreeMap<String, ClientInfo> userNameToClientMap = new TreeMap<String, ClientInfo>();
            for (ClientInfo clientInfo : clientInfos) {
                if (clientInfo.getUser() != null) {
                    userNameToClientMap.put(clientInfo.getUser().getName(), clientInfo);
                }
            }
            ret = userNameToClientMap.values().toArray(new ClientInfo[userNameToClientMap.size()]);
        }
        return ret;
    }

}
